<template>
	<view class="form-item">
		<picker :range-key="itemLabel" :range="items" @change="bindPickerChange" :value="changeIndex"
			:disabled="disabled">
			<view class="input-item" :class="{'fullinput': !showIcon}"><text
					:class="[changeIndex !== '' && items[changeIndex] ? 'changed' : 'placeholder']">{{changeIndex !== '' && items[changeIndex][itemLabel] || placeholder}}</text>
			</view>
		</picker>
		<template v-if="showIcon">
			<uni-icons v-if="changeIndex === ''" type="bottom" size="16" color="#c0c4cc">
			</uni-icons>
			<uni-icons v-else-if="!disabled" @click="clearValue" type="clear" size="16" color="#c0c4cc"></uni-icons>
		</template>
	</view>
</template>

<script>
	export default {
		props: {
			placeholder: {
				type: String,
				default: '请选择'
			},
			value: String,
			disabled: Boolean,
			itemLabel: {
				type: String,
				default: 'label'
			},
			itemValue: {
				type: String,
				default: 'value'
			},
			showIcon: {
				type: Boolean,
				default: true
			},
			items: {
				type: Array,
				default () {
					return []
				}
			}
		},
		data() {
			return {
				changeIndex: ''
			}
		},
		watch: {
			value: {
				async handler(n) {
					console.log('nnn', n)
					this.initValue()
					
				},
				immediate: true
			},
			items () {
				this.initValue()
			}
		},
		methods: {
			initValue () {
				if (!this.value) {
					this.changeIndex = ''
					return
				}
				console.log('this.items', this.items, this.itemValue)
				let index = this.items.findIndex(d => d[this.itemValue] == this.value)
				console.log('index', index)
				if (index != -1) {
					this.changeIndex = index
				} else {
					this.changeIndex = ''
				}
			},
			bindPickerChange(e) {
				this.changeIndex = e.detail.value
				let obj = this.items[this.changeIndex]
				this.$emit('input', obj[this.itemValue])
			},
			clearValue() {
				this.changeIndex = ''
				this.$emit('input', '')
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep {
		uni-picker {
			width: 100%;
		}

		picker {
			width: 100%;
		}
	}

	.form-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding-right: 5px;
		height: 100%;

		&.disabled {
			cursor: not-allowed;
		}

		.input-item {
			width: calc(100% - 80px);
			padding: 0 10px;

			.changed {
				color: #333;
			}
			&.fullinput {
				width: calc(100% - 50px);
			}
		}

		.placeholder {
			color: #999999;
		}
	}
</style>
